import logging
from runtime.nodelogger import NodeLogger

from datastore.resource import Resource
from datastore.uri import Uri
from runtime.service import Service

from spear.a2p_service import A2PServiceAPI
from datastore.spaces import Spaces


   
class ApplicationListService(Service):
    
    SPEAR_CURRENT_APPLICATION_LIST = 'SPEAR Current Application List'
    UNABLE_TO_FIND_ANY_CURRENT_SPEAR_APPLICATIONS = 'Unable to find any current SPEAR applications'
    
    def cb_start(self, uri, action, res):
         
        #self.logger = NodeLogger.getLogger('yarra.examples.application_list.ApplicationList')
                         
        self.spaces.set_process(Uri('external:adaptor/application-list/'),self.cb_list)   
        self.spaces.set_process(Uri('external:adaptor/application-list'),self.cb_list)
          
    def cb_stop (self):
        pass

    def cb_list(self, uri, action, res):
   
        if action == Spaces.ACTION_EXISTS: 
            return True
        elif action == Spaces.ACTION_GET:
            self.logger.log(logging.DEBUG, "Requesting SPEAR Application List")
            
            rs = Resource(type='term:eplanning/adaptor/application-list/data')
            rs.dc_title("Current SPEAR Application List")
            rs.dc_description("Listing of current active SPEAR Applications.")
            rs.applications = {}
            app_list_rs = self.get_application_list()
            if app_list_rs: 
                if app_list_rs.has_var("apps_dict_dict"):
                    apps_dict = app_list_rs.get_var("apps_dict_dict")
                    rs.applications = apps_dict
            else :
                rs.message = ApplicationListService.UNABLE_TO_FIND_ANY_CURRENT_SPEAR_APPLICATIONS        
                
            rs.h1_header = ApplicationListService.SPEAR_CURRENT_APPLICATION_LIST
            return rs
        else:
            return
        
    def get_application_list(self):
        a2p = A2PServiceAPI(self.spaces)
        app_list_rs = a2p.get_application_list(is_current=True)
        return app_list_rs